/**
 * 
 */
package t4j.concurrency.waxomatic;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

class Car{
	private boolean waxOn = false;
	
	//打蜡
	public synchronized void waxed(){
		waxOn = true;
		notifyAll();//唤醒
	}
	
	//抛光
	public synchronized void buffed(){
		waxOn = false;
		notifyAll();
	}
	
	//等到打蜡
	public synchronized void waitForWaxing() throws InterruptedException{
		while(waxOn == false)
			wait();//挂起
		
	}
	//等待抛光
	public synchronized void waitForBuffing() throws InterruptedException{
		while(waxOn == true)
			wait();
		
	}
}

class WaxOn implements Runnable{

	private Car car;

	public WaxOn(Car c) {
		car = c;
	}

	@Override
	public void run() {
		try {	
			while(!Thread.interrupted()){
			
				System.out.println("Wax On!");
				
				TimeUnit.MILLISECONDS.sleep(200);
				
				car.waxed();////打蜡
				
				car.waitForBuffing();//等待抛光
			}
			
		} catch (InterruptedException e) {
			System.out.println("WaxOn Exiting via interrupt");
		}
		
		System.out.println("Ending Wax On task");
	}
}

class WaxOff implements Runnable{
	private Car car;
	
	public WaxOff(Car c) {
		car = c;
	}
	
	public void run(){
		try {
			while(true){
				
				car.waitForWaxing();//等到打蜡
				
				System.out.println("Wax Off");
				
				TimeUnit.MILLISECONDS.sleep(200);
				
				car.buffed();//抛光
			}
		} catch (InterruptedException e) {
			System.out.println("WaxOff Exiting via interrupt");
		}
		
		System.out.println("Ending Wax Off task");
	}
}



public class WaxOMatic {
	public static void main(String[] args) throws Exception {
		
		Car car = new Car();
		
		ExecutorService exec = Executors.newCachedThreadPool();
		
		exec.execute(new WaxOff(car));
		
		exec.execute(new WaxOn(car));
		
		TimeUnit.SECONDS.sleep(5);
		
		exec.shutdownNow();
	}
}
